import 'package:flutter/material.dart';
import 'random_words_widget.dart'; // 导入 RandomWordsWidget 组件

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyHomePage> {
  int counter = 0;

  void incrementCounter() {
    setState(() {
      counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My App'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Builder(builder: (context) {
              return ElevatedButton(
                onPressed: () {
                  // 通过 GlobalKey 获取 State 对象
                  _MyAppState state = context.findAncestorStateOfType<_MyAppState>()!;
                  // 调用 State 中的方法
                  state.incrementCounter();
                },
                child: Text('Increment Counter'),
              );
            }),
            Text('Counter: $counter'),
            RandomWordsWidget(), // 添加 RandomWordsWidget
          ],
        ),
      ),
    );
  }
}